package com.chen.listener;

import com.chen.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import static com.chen.constant.RedisConstants.MALL_ORDER_TIEM;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    private OrderService orderService;

    /**
     * 针对redis数据失效事件，进行数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            String key = message.toString();
            log.info("监听到key失效了:{} " + key);
            orderService.UpdateTimeOutOrder(substring(key));
        } catch (Exception e) {
            System.out.println("错误异常");
            e.printStackTrace();
        }
    }

    public String substring(String str) {
        String prefix = MALL_ORDER_TIEM;
        // 判断字符串是否以指定前缀开始
        if (str.startsWith(prefix)) {
            // 计算订单号开始的位置
            int orderNumberStartIndex = prefix.length();
            // 提取订单号
            String orderNumber = str.substring(orderNumberStartIndex);
            log.info("监听到超时未支付订单：{}", orderNumber);
            return orderNumber;
        } else {
            System.out.println("The string does not start with the specified prefix.");
        }
        return null;
    }
}

